package com.netty.demo.nio;

import com.netty.demo.nio.handler.impl.LoginRequestHandler;
import com.netty.demo.nio.handler.impl.ServerMessageReceiveHandler;
import com.netty.demo.protocol.packet.PacketDecoder;
import com.netty.demo.protocol.packet.PacketEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyServer {
    public static void main(String[] args){
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        serverBootstrap
                .group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel ch){
//                        ch.pipeline().addLast(new StringDecoder());
//                        ch.pipeline().addLast(new FirstServerChannleHandler());
//                        ch.pipeline().addLast(new ServerHandler());
                        ch.pipeline().addLast(new PacketDecoder());
                        ch.pipeline().addLast(new LoginRequestHandler());
                        ch.pipeline().addLast(new ServerMessageReceiveHandler());
                        ch.pipeline().addLast(new PacketEncoder());

                    }


                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception{
                        super.exceptionCaught(ctx, cause);
                        System.out.println("*********************");
                    }
                });
        bind(serverBootstrap, 1000);
    }

    private static void bind(final ServerBootstrap serverBootstrap, final int port){
        serverBootstrap.bind(port).addListener((future) -> {
            if (future.isSuccess()) {
                System.out.println("端口[" + port + "]绑定成功!");
            } else {
                System.err.println("端口[" + port + "]绑定失败!");
                bind(serverBootstrap, port + 1);
            }
        });
    }
}
